import wx
from wxpyview.ui.core.common.exceptions import *
from wxpyview.ui.core.MainUIGenerator import *
from wxpyview.ui.core.DialogUIGenerator import *

class View:
    def __init__(self):
        self.main_ui_generator = MainUIGenerator()
        self.dlg_ui_generator = DialogUIGenerator()
        self.meta_widget_tree = self.main_ui_generator.getMetaWidgetTree()

    def SimpleInit(self, redirect=False):
        self.wxApplication = wx.PySimpleApp(redirect)
    
    def Parse(self, resource_path):
        self.main_ui_generator.parse(resource_path)
        self.top_widget_object = self.main_ui_generator.createRealWidgets()

    def Run(self):
        if self.top_widget_object == None:
            raise Exception

        self.top_widget_object.Show()
        self.wxApplication.MainLoop()
        
    def SetEventHandler(self, name, event, handler, head_name=None):       
        widget_object = self.FindWidgetByName(name)
        
        # TODO: Check whether widget_object is None.
        #       To say in other words, user specified name to a element tag in rc xml file.

        head_object = self.FindWidgetByName(head_name)

        if head_object != None:
            head_object.Bind(event, handler, widget_object)
        else:
            widget_object.Bind(event, handler)

    def FindWidgetByName(self, name):
        return self.meta_widget_tree.getWidgetByName(name)
    
    def LoadDialog(self, src):       
        self.dlg_ui_generator.parse(src)

    def CreateDialog(self, name):
        return self.dlg_ui_generator.createRealWidgets(name)